﻿using PPSMS_DAL;
using PPSMS_Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PPSMS_BLL;

public class TrendsControl_BLL
{
    private InverterStatistics_DAL inverterStatistics_DAL = new InverterStatistics_DAL();

    private InverterStatus_DAL inverterStatus_DAL = new InverterStatus_DAL();

    private StationStatistics_DAL statationStatistics_DAL = new StationStatistics_DAL();

    private WeatherInfo_DAL weatherInfo_DAL = new WeatherInfo_DAL();

    /// <summary>
    /// 获取指定年份中每月的平均功率
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public Dictionary<string, double> SelectMonthPower(string date, int Id)
    {
        string year = date.Substring(0, 4).ToString();
        var result = inverterStatistics_DAL.SelectAllByDate(year, Id);
        var monthDictionary = new Dictionary<string, double>();

        // 初始化月份字典
        for (int i = 1; i <= 12; i++)
        {
            monthDictionary.Add(i.ToString(), 0);
        }

        string oldMonth = "";
        int count = 0;
        foreach (var item in result)
        {
            string month = item.Date.Substring(5, 2);
            month = int.Parse(month).ToString();
            // 更新当前月份的平均值
            if (month != oldMonth)
            {
                if (count > 0)
                {
                    monthDictionary[oldMonth] = monthDictionary[oldMonth] / count;
                }
                count = 1; // 重置计数
            }
            else
            {
                count++;
            }
            oldMonth = int.Parse(month).ToString();

            // 如果月份在字典中，则累加
            if (monthDictionary.ContainsKey(month))
            {
                monthDictionary[month] += (double)item.DailyEnergy; // 假设使用 DailyEnergy
            }
        }

        // 计算最后一个月份的平均值
        if (count > 0)
        {
            monthDictionary[oldMonth] = monthDictionary[oldMonth] / count;
        }

        return monthDictionary;
    }

    /// <summary>
    /// 获取指定月份中每天的功率
    /// </summary>
    /// <returns></returns>
    public Dictionary<int, double> SelectDayPower(string date, int Id)
    {
        string month = date.Substring(0, 7).ToString();
        List<InverterStatistics>? result;
        result = inverterStatistics_DAL.SelectAllByDate(month, Id);
        var dictionary = new Dictionary<int, double>();

        // 初始化每天字典，假设该月有31天
        for (int i = 1; i <= 31; i++)
        {
            dictionary.Add(i, 0);
        }

        int[] dayCounts = new int[32]; // 用于统计每一天的记录数

        foreach (var item in result)
        {
            if (item.DailyEnergy != null)
            {
                var Power = item.DailyEnergy;
                var day = int.Parse(item.Date.Substring(8, 2));

                // 累加每天的能量值
                if (dictionary.ContainsKey(day))
                {
                    dictionary[day] += (double)Power;
                    dayCounts[day]++; // 计数
                }
            }
        }

        // 计算每天的平均值
        for (int day = 1; day <= 31; day++)
        {
            if (dayCounts[day] > 0)
            {
                dictionary[day] /= dayCounts[day]; // 平均值
            }
        }

        return dictionary;
    }

    /// <summary>
    /// 获取指定天中每小时的平均功率
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public Dictionary<string, double> SelectHourPower(string date, int Id)
    {
        string hour = date.Substring(0, 10).ToString();
        var result = inverterStatus_DAL.SelectAllByDate(hour, Id);
        var hourDictionary = new Dictionary<string, double>();
        for (int i = 1; i <= 24; i++)
        {
            hourDictionary.Add(i.ToString(), 0);
        }
        return ExtractTimeData(result, hourDictionary,11,2);
    }

    /// <summary>
    /// 获取指定小时中每分钟的功率
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public Dictionary<string, double> SelectMinutePower(string date, int Id)
    {
        string minute = date.Substring(0, 13).ToString();
        var result = inverterStatus_DAL.SelectAllByDate(minute, Id);
        var minuteDictionary = new Dictionary<string, double>();

        // 初始化每一分钟的累计值
        for (int i = 1; i <= 60; i++)
        {
            minuteDictionary.Add(i.ToString(), 0); // 保证分钟是两位数
        }
        return ExtractTimeData(result, minuteDictionary, 14, 2);
    }

    /// <summary>
    /// 从数据列表中提取特定时间段的功率信息
    /// </summary>
    /// <param name="result"></param>
    /// <param name="timeDictionary"></param>
    /// <param name="startIndex"></param>
    /// <param name="length"></param>
    /// <returns></returns>
    private static Dictionary<string, double> ExtractTimeData(List<InverterStatus> result, Dictionary<string, double> timeDictionary,int startIndex, int length)
    {
        string oldTime = "";
        int count = 0;
        foreach (var item in result)
        {
            string newTime = item.Timestamp.Substring(startIndex, length);
            newTime = (int.Parse(newTime)).ToString();
            if (newTime != oldTime)
            {
                if (count > 0)
                {
                    if (timeDictionary.ContainsKey(oldTime))
                    {
                        timeDictionary[oldTime] = timeDictionary[oldTime] / count;
                    }
                   
                }
                count = 1;
            }
            else
            {
                count++;
            }
            oldTime = int.Parse(newTime).ToString();

            //如果时间段在字典中，则累加
            if (timeDictionary.ContainsKey(newTime))
            {
                timeDictionary[newTime] += (double)item.AveragePower;
            }
        }

        // 计算最后一个时间段的平均值
        if (count > 0)
        {
            if (timeDictionary.ContainsKey(oldTime))
            {
                timeDictionary[oldTime] = timeDictionary[oldTime] / count;
            }
            
        }
        return timeDictionary;
    }

    /// <summary>
    /// 获取所有年份的总发电量
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public Dictionary<string,double> SelectYearPowerGeneration(string date)
    {
        var result = statationStatistics_DAL.SelectAllByDate(date);
        var yearDictionary = GetPowerGeneration(2014, 2024, "ALL", 0, 4);     
        return yearDictionary;
    }

    /// <summary>
    /// 获取指定年份中每月的总发电量
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public Dictionary<string, double> SelectMonthPowerGeneration(string date)
    {
        return GetPowerGeneration(1,12,date.Substring(0, 4), 5, 2);
    }

    /// <summary>
    /// 获取指定月份中每天的总发电量
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public Dictionary<string, double> SelectDayPowerGeneration(string date)
    {
        return GetPowerGeneration(1,31,date.Substring(0, 7), 8, 2);
    }

    /// <summary>
    /// 获取指定天中每小时的总发电量
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public Dictionary<string, double> SelectHourPowerGeneration(string date)
    {       
        return GetPowerGeneration(1,24,date.Substring(0, 10), 11, 2);
    }

    /// <summary>
    /// 截取日期字符串中特定位置的字符串，并提取数据
    /// 例如：2021-01-01 00:00:00 截取年份，提取2021年的数据
    /// </summary>
    /// <param name="date"></param>
    /// <param name="startIndex"></param>
    /// <param name="length"></param>
    /// <returns></returns>
    private Dictionary<string, double> GetPowerGeneration(int start, int stop,string date, int startIndex, int length)
    {
        var result = statationStatistics_DAL.SelectAllByDate(date);
        var dictionarys = new Dictionary<string, double>();
        for(int i = start; i<= stop; i++)
        {
            dictionarys.Add(i.ToString(),0);
        }
        return ExtractData(dictionarys,result, startIndex, length);
    }

    /// <summary>
    /// 从数据列表中提取特定日期的发电量信息
    /// </summary>
    /// <param name="result"></param>
    /// <param name="startIndex"></param>
    /// <param name="length"></param>
    /// <returns></returns>
    private static Dictionary<string, double> ExtractData(Dictionary<string, double> dictionarys,List<StationStatistics> result, int startIndex, int length)
    {
        var dictionary = dictionarys;
        string oldTime = "";
        int count = 0;
        foreach (var item in result)
        {
            string newTime = item.Date.Substring(startIndex, length);
            newTime = int.Parse(newTime).ToString();
            if (newTime != oldTime)
            {
                if (count > 0)
                {
                    if (dictionarys.ContainsKey(oldTime))
                    {
                        dictionarys[oldTime] = dictionarys[oldTime]; // count;
                    }
                }
                count = 1;
            } 
            else
            {
                count++;
            }
            oldTime = int.Parse(newTime).ToString();

            //如果时间段在字典中，则累加
            if (dictionarys.ContainsKey(newTime))
            {
                dictionarys[newTime] += (double)item.TotalEnergyProduced;
            }
        }

        // 计算最后一个时间段的平均值
        if (count > 0)
        {
            dictionarys[oldTime] = dictionarys[oldTime]; // count;
        }
        return dictionarys;
    }
   
    /// <summary>
    /// 获取所有年份的总辐照度
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public Dictionary<string, double> SelectYearIrradiance(string date)
    {
        //var result = weatherInfo_DAL.SelectAllByDate(date);
        var yearDictionary = SelectIrradiance(2014,2024, "ALL", 0, 4);
        return yearDictionary;
    }

    /// <summary>
    /// 获取指定年份中每月的辐照度
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public Dictionary<string, double> SelectMonthIrradiance(string date)
    {
        return SelectIrradiance(1,12,date.Substring(0, 4), 5, 2); // 获取每月辐照度
    }

    /// <summary>
    /// 获取指定月份中每天的的辐照度
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public Dictionary<string, double> SelectDayIrradiance(string date)
    {
        return SelectIrradiance(1,31,date.Substring(0, 7), 8, 2); // 获取每天辐照度
    }

    /// <summary>
    /// 获取指定天中每小时的辐照度
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public Dictionary<string, double> SelectHourIrradiance(string date)
    {//yyyy-MM-dd HH:mm:ss
        return SelectIrradiance(1,24,date.Substring(0, 10), 11, 2); // 获取每小时辐照度
    }

    /// <summary>
    /// 截取日期字符串中特定位置的字符串，并提取数据
    /// 例如：2021-01-01 00:00:00 截取年份，提取2021年的数据
    /// </summary>
    /// <param name="date"></param>
    /// <param name="startIndex"></param>
    /// <param name="length"></param>
    /// <returns></returns>
    public Dictionary<string, double> SelectIrradiance(int start, int stop, string date, int startIndex, int length)
    {
        var result = weatherInfo_DAL.SelectAllByDate(date);
        var dictionarys = new Dictionary<string, double>();
        for (int i = start; i <= stop; i++)
        {
            dictionarys.Add(i.ToString(), 0);
        }
        return ExtractWeatherInfoData(dictionarys,result, startIndex, length);
    }

    /// <summary>
    /// 从数据列表中提取特定日期的辐照度信息
    /// </summary>
    /// <param name="result"></param>
    /// <param name="v1"></param>
    /// <param name="v2"></param>
    /// <returns></returns>
    private Dictionary<string, double> ExtractWeatherInfoData(Dictionary<string, double> Dictionarys ,List<WeatherInfo> result, int v1, int v2)
    {
        var Dictionary = Dictionarys;
        foreach (var item in result)
        {
            string key = item.Timestamp.Substring(v1, v2);
            key = int.Parse(key).ToString();
            if (Dictionary.ContainsKey(key))
            {
                //Dictionary.Add(key, (double)item.Irradiance);
                Dictionary[key] = (double)item.Irradiance;
            }        
        }
        return Dictionary;
    }

}

